package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

  @Autowired
  private EmployeeMapper employeeMapper;

  /**
   * 员工登录
   *
   * @param employeeLoginDTO
   * @return
   */
  public Employee login(EmployeeLoginDTO employeeLoginDTO) {
      String username = employeeLoginDTO.getUsername();
      String password = employeeLoginDTO.getPassword();

      //1、根据用户名查询数据库中的数据
      Employee employee = employeeMapper.getByUsername(username);

      //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
      if (employee == null) {
          //账号不存在
          throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
      }

      //密码比对, 进行md5加密，然后再比对
      password = DigestUtils.md5DigestAsHex(password.getBytes());
      if (!password.equals(employee.getPassword())) {
          //密码错误
          throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
      }

      if (employee.getStatus() == StatusConstant.DISABLE) {
          //账号被锁定
          throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
      }

      //3、返回实体对象
      return employee;
  }
  
  /**
   * 添加员工
   * @return
   */
  public void inster(EmployeeDTO employeeDTO) {
    Employee employee = new Employee();
    // employee.setUsername(employeeDTO.getUsername());
    // employee.setName(employeeDTO.getName());
    // employee.setSex(employeeDTO.getSex());
    // employee.setPhone(employeeDTO.getPhone());
    
    // 使用对象属性拷贝 简化上面代码
    BeanUtils.copyProperties(employeeDTO, employee);
    employee.setStatus(StatusConstant.ENABLE); // 设置状态
    // 设置密码为md5加密之后的 默认123456
    employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
    // 设置创建时间和修改时间
    // employee.setCreateTime(LocalDateTime.now());
    // employee.setUpdateTime(LocalDateTime.now());
    
    // 从本地线程中获取到员工id, 设置创建人和修改人
    // Long empId = BaseContext.getCurrentId();
    // employee.setCreateUser(empId);
    // employee.setUpdateUser(empId);
    
    employeeMapper.inster(employee);
  }
  
  
  /**
   * 员工分页查询
   * @param queryDTO
   * @return
   */
  @Override
  public PageResult page(EmployeePageQueryDTO queryDTO) {
    // PageHerper 插件分页
    PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
    
    Page<Employee> page = employeeMapper.page(queryDTO);
    long total = page.getTotal();
    List<Employee> records = page.getResult();
    
    return new PageResult(total, records);
  }
  
  /**
   * 启用禁用员工状态
   * @param id
   * @param code
   */
  @Override
  public void changeStatus(Long id, Integer code) {
    // update employee set status = ? where id = ?;
    
    // 构造实体对象，动态更新 增强通用性
    // Employee employee = new Employee();
    // employee.setStatus(code);
    // employee.setId(id);
    
    Employee employee = Employee.builder()
        .id(id)
        .status(code)
        // .updateTime(LocalDateTime.now())
        // .updateUser(BaseContext.getCurrentId())
        .build();
    employeeMapper.update(employee);
  }
  
  /**
   * 修改员工信息
   * @param employeeDTO
   */
  @Override
  public void update(EmployeeDTO employeeDTO) {
    Employee employee = new Employee();
    BeanUtils.copyProperties(employeeDTO, employee);
    // employee.setUpdateTime(LocalDateTime.now());
    // employee.setUpdateUser(BaseContext.getCurrentId());
    
    employeeMapper.update(employee);
  }
  
  /**
   * 根据id查询员工信息
   * @param id
   */
  @Override
  public Employee findById(Long id) {
    Employee employee = employeeMapper.findById(id);
    // 判断查询的id是否存在， 否则抛出异常
    if(employee == null) throw new AccountNotFoundException(MessageConstant.ID_NOT_FOUND);
    // 设置密码为空
    employee.setPassword(null);
    return employee;
  }
  
  /**
   * 修改员工密码。
   *
   * @param passwordEditDTO 包含修改密码所需信息的数据传输对象，包括员工ID、旧密码和新密码
   * @return
   */
  @Override
  public void editPwd(PasswordEditDTO passwordEditDTO) {
    // 1.查找是否有改员工
    Employee employee = employeeMapper.findById(passwordEditDTO.getEmpId());
    System.out.println(employee);
    if(employee != null) {
      // 2.旧密码比对
      String userIptPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
      if(userIptPwd.equals(employee.getPassword())) {
        // 3.密码相同，设置新密码
        System.out.println("密码相同，设置新密码："+ passwordEditDTO.getOldPassword());
        String newPwd = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        Employee employee1 = Employee.builder().id(employee.getId()).password(newPwd).build();
        employeeMapper.update(employee1);
      }else {
        // 抛出密码错误异常
        throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
      }
    } else {
      // 抛出账号不存在异常
      throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
    }
    
  }
}
